package cn.gx.kevin.controller;

import cn.gx.kevin.common.thread.OperatorDataHolder;
import cn.gx.kevin.config.LogInterceptor;
import cn.gx.kevin.domain.RoleMenu;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.gx.kevin.common.annotation.ApiDescript;
import cn.gx.kevin.common.annotation.ApiParams;
import cn.gx.kevin.common.annotation.ApiParamsDesc;
import cn.gx.kevin.common.annotation.ApiReturnDesc;
import cn.gx.kevin.common.ui.AjaxResult;
import cn.gx.kevin.domain.Func;
import cn.gx.kevin.domain.Role;
import cn.gx.kevin.domain.RoleFunc;
import cn.gx.kevin.service.*;
import cn.gx.kevin.controller.ResetfulBaseController;
import cn.gx.kevin.service.IBaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Generate by Kevin's CodeBuilder
 **/
@ApiDescript("系统角色模块")
@Controller
@RequestMapping(value = "/role")
public class RoleController extends ResetfulBaseController<Role, String> {

    @Resource(name = "funcService")
    IFuncService funcService;

    @Resource(name = "roleFuncService")
    IRoleFuncService rfService;

    @Resource(name = "menuService")
    IMenuService menuService;

    IRoleService roleService;

    @Resource(name = "roleService")
    @Override
    public void setService(IBaseService<Role, String> service) {
        this.service = service;
        roleService = (IRoleService)service;
    }

    @Override
    @RequestMapping(value = "/page/{pageName}", method = RequestMethod.GET)
    public String page(@PathVariable("pageName") String pageName, HttpServletRequest request) throws Exception {
        if("funcMrg".equals(pageName)){
            String roleId = request.getParameter("roleId");
            request.setAttribute("roleId",roleId);
        }
        return super.page(pageName, request);
    }

    @ApiReturnDesc("{ code: '0正确/1异常',message: '信息',data: '数据对象'}")
    @ApiParamsDesc("{id:'id'}")
    @ApiDescript("根据ID查询数据")
    @ApiParams("{'id':''}")
    @Override
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public @ResponseBody AjaxResult get(String id) throws Exception {
        return super.get(id);
    }

    @Override
    @ApiDescript("新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult add(HttpServletRequest request) throws Exception {
        return super.add(request);
    }

    @ApiDescript("更新")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public @ResponseBody AjaxResult update(HttpServletRequest request) throws Exception {
        return super.update(request);
    }

    @ApiDescript("删除")
    @ApiParams("{'idList':'id1,id2'}")
    @RequestMapping(value = "/delete")
    public @ResponseBody AjaxResult delete(HttpServletRequest request) throws Exception {
        return super.delete(request);
    }

    @Override
    protected boolean loadDeleteDataForLog(HttpServletRequest request) {
        return true;
    }

    @ApiDescript("分页多条件可排序查询")
    @ApiParams("{'page':1,'pageSize':15,'_col_sort_fieldName':'asc'}")
    @ApiParamsDesc("{page:'当前页',pageSize:'页大小',_col_sort_fieldName:'desc/asc，_col_sort_为前缀标志，fieldName为需要排序的字段名'}")
    @RequestMapping(value = "/list")
    public @ResponseBody AjaxResult list(HttpServletRequest request) throws Exception {
        return super.list(request);
    }

    @Override
    protected Map<String, Object> setListParams(HttpServletRequest request) throws Exception {
        Map<String, Object> map = super.setListParams(request);
        String roleName = request.getParameter("roleName");
        if(StringUtils.isNotEmpty(roleName)){
            map.put("roleName",roleName);
        }
        return  map;
    }

    @ApiDescript("非分页多条件/排序普通查询")
    @ApiParams("{}")
    @RequestMapping(value = "/query")
    public @ResponseBody AjaxResult query(HttpServletRequest request) throws Exception {
        return super.query(request);
    }

    /*
              * 页面 views/base/entityPath 文件夹路径
     * ***/
    @Override
    public String setPageModelPath(HttpServletRequest request) {
        // TODO Auto-generated method stub
        return "base" + File.separator + entityPath;
    }

    @Override
    protected void onRequestPage(String pageName, HttpServletRequest request) throws Exception {
        if ("funcMrg".equals(pageName)) {
            JSONArray menuJson = menuService.getMenuJsonByPid("0");
            request.setAttribute("menuJson", menuJson);
        }
        super.onRequestPage(pageName, request);
    }


    @ApiDescript("加载菜单下所有的功能列表")
    @ApiParams("{idList:'id1,id2',roleId:''}")
    @ApiParamsDesc("{idList:'菜单id',roleId:'角色id'}")
    @RequestMapping(value = "/loadFunc", method = RequestMethod.POST)
    public @ResponseBody AjaxResult loadFunc(HttpServletRequest request) throws Exception {

        String idList = request.getParameter("idList");
        Map<String, Object> params = new HashMap<String, Object>();
        List<String> menuIds = new ArrayList<String>();

        if (idList.contains(",")) {
            String[] tmp = idList.split(",");
            for (int i = 0, len = tmp.length; i < len; ++i) {
                menuIds.add(tmp[i]);
            }
        } else if (StringUtils.isNotEmpty(idList)) {
            menuIds.add(idList);
        }
        if (menuIds.size() > 0) {
            params.put("menuIds", menuIds);
        }

        Map<String, String> order = new HashMap<String, String>();
        order.put("menu_id", "asc");
        params.put("orderColumn", order);
        List<Func> funcList = funcService.selectParam(params);

        String roleId = request.getParameter("roleId");

        //查询角色下的功能，如果有菜单筛选，则设置菜单id条件
        Map<String, Object> roleFuncPrs = new HashMap<String, Object>();
        roleFuncPrs.put("roleId", roleId);
        if (menuIds.size() > 0) {
            roleFuncPrs.put("menuIds", menuIds);
        }
        List<RoleFunc> rfList = rfService.selectParam(roleFuncPrs);
        JSONObject rRobj = new JSONObject();
        for (RoleFunc rf : rfList) {
            rRobj.put(rf.getFuncId(), true);
        }
        JSONObject resObj = new JSONObject();
        resObj.put("funcList", funcList);
        resObj.put("roleFuncObj", rRobj);
        //查询角色菜单
        List<RoleMenu> roleMenuList =   this.roleService.selectMenusByRole(Long.valueOf(roleId));
        JSONObject roleMenuObj = new JSONObject();
        for(RoleMenu roleMenu : roleMenuList){
            roleMenuObj.put(roleMenu.getMenuId(),true);
        }
        resObj.put("roleMenuObj", roleMenuObj);
        return returnSuccData(resObj);
    }

    // 功能管理
    @ApiDescript("设置角色的功能")
    @ApiParams("{funcs:'id1,id2',menus:'id1,id2',roleId:''}")
    @ApiParamsDesc("{funcs:'功能id',menus:'菜单id',,roleId:'角色id'}")
    @RequestMapping(value = "/funcMrg", method = RequestMethod.POST)
    public @ResponseBody AjaxResult funcMrg(HttpServletRequest request) throws Exception {
        String roleId = request.getParameter("roleId");
        String funcs = request.getParameter("funcs");
        String menus = request.getParameter("menus");
        List<RoleFunc> list = new ArrayList<RoleFunc>();
        if (StringUtils.isNotEmpty(funcs)) {
            list = JSONArray.parseArray(funcs, RoleFunc.class);
        }
        String roleMenus = request.getParameter("roleMenus");
        List<RoleMenu> roleMenuList = new ArrayList<>();
        if(StringUtils.isNotEmpty(roleMenus)){
            String [] tmp = roleMenus.split(";");
            for(String s : tmp){
                if(!"".equals(s) && !"undefined".equals(s)) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setMenuId(s);
                    roleMenu.setRoleId(roleId);
                    roleMenuList.add(roleMenu);
                }
            }
        }
        rfService.setRoleFunc(roleId, list, menus,roleMenuList);
        //将需要记录的数据放入线程变量
        if(LogInterceptor.currentRequestNeed2Log()){
            Role role =  roleService.get(roleId);
            String roleName = role.getRoleName();
            OperatorDataHolder.setDataObject("调整了角色["+roleName+"]的权限！");
        }
        return this.returnSuccess();

    }
}
